<template>
  <el-card class="form-container" shadow="never">
    <el-form :model="video" :rules="rules" ref="videoFrom" label-width="100px">
      <el-form-item label="视频链接：" prop="url">
        <el-input
          size="small"
          v-model="video.url"
          :disabled="isEdit"
        ></el-input>
      </el-form-item>
      <el-form-item label="视频封面：" prop="cover">
        <single-upload v-model="video.cover"></single-upload>
      </el-form-item>
      <el-form-item label="视频标题：" prop="title">
        <el-input
          size="small"
          v-model="video.title"
          maxlength="80"
          show-word-limit
          placeholder="请填写标题"
        ></el-input>
      </el-form-item>
      <el-form-item label="类型：" prop="videoType">
        <el-radio-group v-model="video.videoType" :disabled="isEdit">
          <el-radio :label="1">自制</el-radio>
          <el-radio :label="0">转载</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="视频分区：" prop="pid">
        <el-cascader
          size="small"
          v-model="selectPartitionValue"
          :options="partitionOptions"
          style="width: 100%;"
        >
        </el-cascader>
        <div
          class="el-icon-warning partition-tip"
          v-if="selectPartitionValue && tip"
        >
          {{ tip }}
        </div>
      </el-form-item>

      <el-form-item label="标签：" prop="tags">
        <div class="tag-input-wrp">
          <div class="input-container">
            <div class="tag-pre-wrp">
              <div
                class="label-item-v2-container"
                v-for="(tag, index) in video.tags"
                :key="index"
                @click="removeTag(tag)"
              >
                <p class="label-item-v2-content">{{ tag }}</p>
                <i class="el-icon-close"></i>
              </div>
            </div>
            <div class="input-instance">
              <input
                type="text"
                maxlength="20"
                placeholder="按回车键Enter创建标签"
                class="input-val"
                v-model="tempTagName"
                @keypress.enter="keyPressHandle"
              />
            </div>
            <p class="tag-last-wrp">
              还可以添加{{ maxTagCount - video.tags.length }}个标签
            </p>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="简介：">
        <el-input
          type="textarea"
          size="small"
          maxlength="2000"
          :rows="8"
          v-model="video.remark"
          placeholder="简单介绍您的视频"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('videoFrom')"
          >提交</el-button
        >
        <el-button v-if="!isEdit" @click="resetForm('videoFrom')"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { createVideo, updateVideo, getVideo } from "@/api/video";
import { queryAll } from "@/api/tag";
import SingleUpload from "@/components/Upload/singleUpload";
import { fetchListWithChildren } from "@/api/partition";

const defaultVideo = {
  uvid: null,
  uuid: null,
  // 分区code
  pid: null,
  partitionName: null,
  title: null,
  // 默认自制
  videoType: 1,
  // 是否可转载
  rePrintPower: false,
  fromUrl: null,
  cover: null,
  url: null,
  remark: null,
  tags: [],
};
export default {
  name: "videoDetail",
  components: { SingleUpload },
  props: {
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      video: Object.assign({}, defaultVideo),
      rules: {
        title: [
          { required: true, message: "请输入视频标题", trigger: "blur" },
          { min: 2, max: 140, message: "长度在 1 到 8个字符", trigger: "blur" },
        ],
        // 分区code
        pid: { required: true, message: "请选择分区", trigger: "blur" },
        partitionName: {
          required: true,
          message: "请选择分区",
          trigger: "blur",
        },
        // 默认自制
        videoType: {
          required: true,
          message: "请输入视频类型",
          trigger: "blur",
        },
        // 是否可转载
        cover: { required: true, message: "请选择视频封面", trigger: "blur" },
        url: { required: true, message: "请选择视频文件", trigger: "blur" },
        remark: { required: true, message: "请输入简介", trigger: "blur" },
      },
      selectPartitionValue: [],
      tip: null,
      partitionOptions: [],
      tempTagName: null,
      maxTagCount: 5,
    };
  },
  mounted() {
    if (this.isEdit) {
      getVideo(this.$route.query.uvid).then((response) => {
        this.video = response.data;
        this.getPartitionList();
      });
    } else {
      this.video = Object.assign({}, defaultVideo);
      this.getPartitionList();
    }
  },
  watch: {
    selectPartitionValue: function (newValue) {
      if (newValue != null) {
        // 二级分区
        this.video.pid = newValue[newValue.length - 1];
        let result = this.getPartitionNameAndTipById(this.video.pid);
        this.video.partitionName = result[0];
        this.tip = result[1];
      } else {
        this.video.pid = null;
        this.video.partitionName = null;
        this.tip = null;
      }
    },
  },
  methods: {
    handleEditCreated() {
      // 注意下面等号用 ==
      if (this.video.pid !== null) {
        // console.log(this.video.pid);
        this.selectPartitionValue = [];
        for (let i = 0; i < this.partitionOptions.length; i++) {
          // console.log(this.partitionOptions[i].value);
          if (this.partitionOptions[i].value == this.video.pid) {
            this.selectPartitionValue.push(this.partitionOptions[i].value);
            return;
          }
          if (
            this.partitionOptions[i].children != null &&
            this.partitionOptions[i].children.length > 0
          ) {
            for (let j = 0; j < this.partitionOptions[i].children.length; j++) {
              // console.log(this.partitionOptions[i].children[j].value);
              if (
                this.partitionOptions[i].children[j].value == this.video.pid
              ) {
                this.selectPartitionValue.push(this.partitionOptions[i].value);
                this.selectPartitionValue.push(
                  this.partitionOptions[i].children[j].value
                );
                return;
              }
              if (
                this.partitionOptions[i].children[j].children != null &&
                this.partitionOptions[i].children[j].children.length > 0
              ) {
                for (
                  let k = 0;
                  k < this.partitionOptions[i].children[j].children.length;
                  k++
                ) {
                  // console.log(this.partitionOptions[i].children[j].children[k].value);
                  if (
                    this.partitionOptions[i].children[j].children[k].value ==
                    this.video.pid
                  ) {
                    this.selectPartitionValue.push(
                      this.partitionOptions[i].value
                    );
                    this.selectPartitionValue.push(
                      this.partitionOptions[i].children[j].value
                    );
                    this.selectPartitionValue.push(
                      this.partitionOptions[i].children[j].children[k].value
                    );
                    return;
                  }
                }
              }
            }
          }
        }
        // console.log(this.selectPartitionValue);
      }
    },
    getPartitionList() {
      fetchListWithChildren().then((response) => {
        let list = response.data;
        this.partitionOptions = [];
        for (let i = 0; i < list.length; i++) {
          let children = [];
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              let cc = [];
              let item = list[i].children[j];
              if (item.children != null && item.children.length > 0) {
                for (let k = 0; k < item.children.length; k++) {
                  const element = item.children[k];
                  cc.push({
                    label: element.partitionName,
                    value: element.id,
                    info: element.info,
                  });
                }
              }
              children.push({
                label: list[i].children[j].partitionName,
                value: list[i].children[j].id,
                info: list[i].children[j].info,
                children: cc.length === 0 ? null : cc,
              });
            }
          }
          this.partitionOptions.push({
            label: list[i].partitionName,
            value: list[i].id,
            info: list[i].info,
            children: children.length === 0 ? null : children,
          });
        }
        // console.log(this.partitionOptions);
        if (this.isEdit) {
          this.handleEditCreated();
        }
      });
    },
    getPartitionNameAndTipById(id) {
      let name = null;
      let tip = null;
      for (let i = 0; i < this.partitionOptions.length; i++) {
        if (this.partitionOptions[i].value == id) {
          name = this.partitionOptions[i].label;
          tip = this.partitionOptions[i].info;
          return [name, tip];
        }
        if (this.partitionOptions[i].children) {
          for (let j = 0; j < this.partitionOptions[i].children.length; j++) {
            if (this.partitionOptions[i].children[j].value == id) {
              name = this.partitionOptions[i].children[j].label;
              tip = this.partitionOptions[i].children[j].info;
              return [name, tip];
            }
            if (this.partitionOptions[i].children[j].children) {
              for (
                let k = 0;
                k < this.partitionOptions[i].children[j].children.length;
                k++
              ) {
                if (
                  this.partitionOptions[i].children[j].children[k].value == id
                ) {
                  name = this.partitionOptions[i].children[j].children[k].label;
                  tip = this.partitionOptions[i].children[j].children[k].info;
                  return [name, tip];
                }
              }
            }
          }
        }
      }
      return [name, tip];
    },
    keyPressHandle() {
      let match = this.video.tags.filter((item) => {
        return item === this.tempTagName;
      });
      if (match.length > 0) {
        this.$message.error("已添加该标签");
        return;
      }
      if (this.maxTagCount - this.video.tags.length === 0) {
        this.$message.error("允许添加的标签已达到上限");
      } else {
        this.video.tags.push(this.tempTagName);
      }
      this.tempTagName = null;
    },
    removeTag(tag) {
      let index = this.video.tags.indexOf(tag);
      this.video.tags.splice(index, 1);
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm("是否提交", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            if (this.isEdit) {
              updateVideo(this.$route.query.uvid, this.video).then(
                (response) => {
                  this.$message({
                    message: "修改成功",
                    type: "success",
                    duration: 1000,
                  });
                  this.$router.back();
                }
              );
            } else {
              createVideo(this.video).then((response) => {
                this.$refs[formName].resetFields();
                this.resetForm(formName);
                this.$message({
                  message: "提交成功",
                  type: "success",
                  duration: 1000,
                });
              });
            }
          });
        } else {
          this.$message({
            message: "验证失败",
            type: "error",
            duration: 1000,
          });
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.video = Object.assign({}, defaultVideo);
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item__label {
  font-weight: bold;
}
/deep/ .el-form-item__content {
  line-height: 24px;
}
.partition-tip {
  background-color: #f4f4f5;
  color: #909399;
  padding: 8px 16px;
  border-radius: 4px;
  text-overflow: ellipsis;
  margin-top:10px;
}
.tag-input-wrp {
  flex: 1;
  // margin-top: 12px;
  .tag-pre-wrp {
    line-height: 24px;
    display: flex;
    flex-wrap: wrap;
    > .label-item-v2-container {
      margin: 4px 6px 4px 0;
    }
  }
  .tag-last-wrp {
    font-size: 14px;
    color: #858585;
    margin: 8px 0 8px 12px;
    cursor: default;
  }
}
.label-item-v2-container {
  background: #00a1d6;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 9px 0 11px;
  cursor: pointer;
  color: #fff;
  max-height: 30px;
  .label-item-v2-content {
    line-height: 30px;
    max-width: 240px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    font-size: 12px;
  }
}
.input-container {
  line-height: 24px;
  background: hsla(0, 0%, 84.7%, 0);
  border: 1px solid #ccd0d7;
  border-radius: 4px;
  padding: 0 12px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  transition: border 0.3s ease;
  .input-instance {
    flex: 1;
    min-width: 200px;
    margin: 6px 0;
    .input-val {
      display: block;
      width: 100%;
      color: #222;
      line-height: 22px;
      height: 22px;
      font-size: 14px;
      outline: 0;
      -webkit-appearance: none;
      -moz-appearance: none;
      appearance: none;
      border: 0;
      background-color: transparent;
    }
  }
}
</style>
